#import urllib2
import re
from settings import Settings
from twill.commands import *

class Radios(object):
    @staticmethod
    def toXML():
        gsURL = Settings.getAttr("gs/statusUrl")
        pURL = Settings.getAttr("plane/statusUrl")
        return '''<?xml version="1.0" encoding="ISO-8859-1"?>
<radios>
    <gs>
        '''+Radios.getSignal(gsURL)+'''
    </gs>
    <p>
        '''+Radios.getSignal(pURL)+'''
    </p>
</radios>'''

    @staticmethod
    def getSignal(url):
        try:
            data = Radios.getContents(url)
            if data is None:
                raise None
            a = data[43].split("\"")
            signal = Radios.toNum(a[2])
            rssi = Radios.toNum(a[4])
            noisef = Radios.toNum(a[6])
            a = data[47].split("\"")
            txrate = float(a[3])
            rxrate = float(a[7])
            chan = Radios.toNum(data[38])
            freq = data[39].split("\"")[3]
            gotit = "True" #success
        except:
            signal = 0
            rssi = 0
            noisef = 0
            txrate = 0
            rxrate = 0
            chan = 0
            freq = 0
            gotit = "False" #fail
        return '''<signal>'''+str(signal)+'''</signal>
        <rssi>'''+str(rssi)+'''</rssi>
        <noisef>'''+str(noisef)+'''</noisef>
        <txrate>'''+str(txrate)+'''</txrate>
        <rxrate>'''+str(rxrate)+'''</rxrate>
        <chan>'''+str(chan)+'''</chan>
        <freq>'''+str(freq)+'''</freq>
        <gotit>'''+str(gotit)+'''</gotit>'''
    
    @staticmethod
    def getContents(url):
        return None
        #TODO: fix this for timeout cases
        if url is None: return None
        go(url)
        data = show()
        if data[0] is '{':return data
        #else login:
        fv("1", "username", "ubnt")
        fv("1", "password", "ubnt")
        submit('0')
        go(url)
        data = show()
        if data[0] is '{':return data
        return None
    
    @staticmethod
    def toNum(input):
        return int(re.sub("[^0-9+.+-]","",input))